<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import request from '../utils/request'

const router = useRouter()

// 标签列表数据
const tags = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 控制添加标签弹窗的显示
const dialogVisible = ref(false)
const newTagName = ref('')

// 控制编辑标签对话框的显示
const editDialogVisible = ref(false)
const editingTag = ref(null)

// 获取标签列表
const getTagList = async () => {
  try {
    const response = await request.get('/api/tags', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })
    if (response.data.code === 200) {
      tags.value = response.data.data.list
      total.value = response.data.data.total
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
  }
}

// 添加标签
const addTag = async () => {
  if (!newTagName.value.trim()) {
    ElMessage.warning('请输入标签名称')
    return
  }
  
  try {
    const response = await request.post('/api/tags', {
      name: newTagName.value.trim()
    })
    if (response.data.code === 200) {
      ElMessage.success('添加成功')
      dialogVisible.value = false
      newTagName.value = ''
      getTagList()
    }
  } catch (error) {
    console.error('添加标签失败:', error)
    ElMessage.error('添加标签失败')
  }
}

// 打开编辑对话框
const openEditDialog = (tag) => {
  editingTag.value = { ...tag }
  editDialogVisible.value = true
}

// 更新标签
// 删除标签
const handleDelete = async (tag) => {
  try {
    await ElMessageBox.confirm('确认删除该标签吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await request.delete(`/api/tags/${tag.id}`)
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      getTagList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除标签失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const updateTag = async () => {
  try {
    const response = await request.put(`/api/tags/${editingTag.value.id}`, {
      name: editingTag.value.tag_name
    })
    if (response.data.code === 200) {
      ElMessage.success('更新成功')
      editDialogVisible.value = false
      editingTag.value = null
      getTagList()
    }
  } catch (error) {
    console.error('更新标签失败:', error)
    ElMessage.error('更新失败')
  }
}

// 处理分页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTagList()
}

// 组件挂载时获取标签列表
onMounted(() => {
  getTagList()
})
</script>

<template>
  <div class="tag-list">
    <div class="header">
      <div class="header-left">
        <el-button type="text" @click="router.push('/')">
          <el-icon><arrow-left /></el-icon>
        </el-button>
        <h2>标签管理</h2>
      </div>
      <el-button type="primary" @click="dialogVisible = true">
        <el-icon><el-icon-plus /></el-icon>
        添加标签
      </el-button>
    </div>

    <el-table :data="tags" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="tag_name" label="标签名称" />
      <el-table-column prop="created_at" label="创建时间" width="180" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="openEditDialog(row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        layout="prev, pager, next"
      />
    </div>

    <!-- 添加标签弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加标签"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form>
        <el-form-item label="标签名称">
          <el-input v-model="newTagName" placeholder="请输入标签名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addTag">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑标签对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑标签"
      width="30%"
    >
      <el-form>
        <el-form-item label="标签名称">
          <el-input v-model="editingTag.tag_name" placeholder="请输入标签名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateTag">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.tag-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header h2 {
  margin: 0;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>